# coding: utf-8
import requests
from 通用方法.utils import base642bin
import cv2
from matplotlib import pyplot as plt, cm
import numpy as np
import os


def load():
    down_path = r'F:\vpnbook\验证码\upanso数据集\原始数据集'
    url = 'https://api.upanso.com/verify/v1'
    for _ in range(1000):
        rep = requests.get(url).json()
        img = rep['data']['img'].replace('data:image/png;base64,', '')
        print(rep['data']['img'])
        base642bin(down_path, str(img))


def verify():
    url = 'https://api.upanso.com/verify/v1/search_verify'
    data = {"verify_str": "j8uo", "verify_code": "6VegJDTjR616OZuerrQF"}
    rep = requests.post(url, json=data).json()
    print(rep)


def show_gray_img(img):
    plt.imshow(img, cmap=cm.gray)
    plt.show()


def gray():
    """
     pip install opencv-python
     https://blog.csdn.net/qq_51985653/article/details/113486737
     https://blog.csdn.net/weixin_41798704/article/details/108382491
    :return:
    """
    img = cv2.imread(r"F:\vpnbook\VerifyCode\upanso_dataset\raw_dataset\ABkqUt.png")
    # 转换为灰度图
    im_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 显示或灰度图
    # show_gray_img(im_gray)
    #
    ret, im_inv = cv2.threshold(im_gray, 150, 255, 0)
    show_gray_img(im_inv)
    print(ret)
    return im_inv


def count_number(num_list, num):
    """
    统计一维数组中某个数字的个数
    :param num_list:
    :param num:
    :return: num的数量
    """
    t = 0
    for i in num_list:
        if i == num:
            t += 1
    return t


def cut_vertical(img_list, c_value=255):
    """
    投影法竖直切割图片的数组
    :param img_list: 传入的数据为一个由（二维）图片构成的数组，不是单纯的图片
    :param c_value: 切割的值 c_value
    :return: 切割之后的图片的数组
    """
    # 如果传入的是一个普通的二值化的图片，则需要首先将这个二值化的图片升维为图片的数组
    if len(np.array(img_list).shape) == 2:
        img_list = img_list[None]
    r_list = []
    for img_i in img_list:
        end = 0
        for i in range(len(img_i.T)):
            if count_number(img_i.T[i], c_value) >= img_i.shape[0]:
                star = end
                end = i
                if end - star > 1:
                    r_list.append(img_i[:, star:end])

    print(r_list)
    return r_list


def spilt_image():
    # 垂直分割投影法分割图片
    img_list = cut_vertical(gray())
    t = 1
    for i in img_list:
        resize_img = cv2.resize(i, (30, 30))  # 重新定义大小
        # 这里可以对切割到的图片进行操作，显示出来或者保存下来
        cv2.imwrite(str(t) + '.jpg', resize_img)
        t += 1


if __name__ == '__main__':
    spilt_image()
